<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>访客统计 - 后台管理系统</title>
    <link rel="stylesheet" href="../styles/styles-main.css">
    <link rel="stylesheet" href="../styles/modules.css">

    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
    <script src="../scripts/api-client.js"></script>
    <script src="../scripts/navbar-main.js"></script>
    <script src="../scripts/visitor-analytics.js"></script>
    <script src="../scripts/sidebar-manager.js"></script>
    <style>
        /* 报表统计页面专用样式 */
        .reports-container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }

        .reports-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
            flex-wrap: wrap;
            gap: 15px;
        }

        .date-filter {
            display: flex;
            align-items: center;
            gap: 15px;
            flex-wrap: wrap;
        }

        .date-input-group {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .date-input-group label {
            font-weight: 600;
            color: #2c3e50;
            white-space: nowrap;
        }

        .date-input {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }

        .filter-btn {
            background: #3498db;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: background 0.3s;
        }

        .filter-btn:hover {
            background: #2980b9;
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 15px;
            margin-bottom: 20px;
        }

        .stat-card {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            text-align: center;
        }

        .stat-value {
            font-size: 2.5em;
            font-weight: bold;
            color: #3498db;
            margin: 10px 0;
        }

        .stat-label {
            color: #7f8c8d;
            font-size: 14px;
        }

        .chart-container {
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            margin-bottom: 30px;
            padding: 20px;
        }

        .chart-title {
            font-size: 1.2em;
            font-weight: 600;
            color: #2c3e50;
            margin-bottom: 20px;
            border-bottom: 2px solid #ecf0f1;
            padding-bottom: 10px;
        }

        .chart-wrapper {
            height: 400px;
            min-height: 300px;
        }

        .ip-stats-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }

        .ip-ranking {
            max-height: 300px;
            overflow-y: auto;
        }

        .ip-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 12px 0;
            border-bottom: 1px solid #ecf0f1;
        }

        .ip-item:last-child {
            border-bottom: none;
        }

        .ip-info {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .ip-address {
            font-family: monospace;
            font-weight: 600;
            color: #2c3e50;
        }

        .ip-region {
            color: #7f8c8d;
            font-size: 12px;
        }

        .ip-count {
            background: #3498db;
            color: white;
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 600;
        }

        .visitor-ratio {
            display: flex;
            justify-content: space-around;
            align-items: center;
            margin-top: 20px;
        }

        .ratio-item {
            text-align: center;
        }

        .ratio-value {
            font-size: 2em;
            font-weight: bold;
            margin: 10px 0;
        }

        .ratio-new {
            color: #27ae60;
        }

        .ratio-return {
            color: #e74c3c;
        }

        .ratio-label {
            color: #7f8c8d;
            font-size: 14px;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .reports-header {
                flex-direction: column;
                align-items: stretch;
            }

            .date-filter {
                justify-content: center;
            }

            .ip-stats-grid {
                grid-template-columns: 1fr;
            }

            .stats-grid {
                grid-template-columns: 1fr;
            }

            .chart-wrapper {
                height: 300px;
            }

            .visitor-ratio {
                flex-direction: column;
                gap: 20px;
            }
        }

        @media (max-width: 480px) {
            .reports-container {
                padding: 10px;
            }

            .date-input-group {
                flex-direction: column;
                align-items: stretch;
            }

            .chart-wrapper {
                height: 250px;
            }
        }

        /* 加载动画 */
        .loading {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 200px;
            color: #7f8c8d;
        }

        .spinner {
            width: 40px;
            height: 40px;
            border: 4px solid #ecf0f1;
            border-top: 4px solid #3498db;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
</head>
<body>
    <div class="container">
        
        <main class="content">
            <div class="reports-container">
                <!-- 页面标题和日期筛选 -->
                <div class="reports-header">
                    <h1>访客统计分析</h1>
                    <div class="date-filter">
                        <div class="date-input-group">
                            <label for="startDate">开始日期:</label>
                            <input type="date" id="startDate" class="date-input">
                        </div>
                        <div class="date-input-group">
                            <label for="endDate">结束日期:</label>
                            <input type="date" id="endDate" class="date-input">
                        </div>
                        <button class="filter-btn" onclick="filterData()">筛选</button>
                        <button class="filter-btn" onclick="resetFilter()" style="background: #95a5a6;">重置</button>
                    </div>
                </div>

                <!-- 统计概览卡片 -->
                <div class="stats-grid">
                    <div class="stat-card">
                        <div class="stat-label">总访问量</div>
                        <div class="stat-value" id="totalVisits">0</div>
                        <div class="stat-label">今日访问: <span id="todayVisits">0</span></div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-label">独立访客</div>
                        <div class="stat-value" id="uniqueVisitors">0</div>
                        <div class="stat-label">新访客: <span id="newVisitors">0</span></div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-label">平均停留时间</div>
                        <div class="stat-value" id="avgDuration">0s</div>
                        <div class="stat-label">跳出率: <span id="bounceRate">0%</span></div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-label">页面浏览量</div>
                        <div class="stat-value" id="pageViews">0</div>
                        <div class="stat-label">人均浏览量: <span id="viewsPerVisitor">0</span></div>
                    </div>
                </div>

                <!-- 每日访问量统计图表 -->
                <div class="chart-container">
                    <div class="chart-title">每日访问量统计</div>
                    <div class="chart-wrapper" id="dailyChart"></div>
                </div>

                <!-- IP统计模块 -->
                <div class="chart-container">
                    <div class="chart-title">IP地域分布统计</div>
                    <div class="ip-stats-grid">
                        <div class="chart-wrapper" id="ipRegionChart"></div>
                        <div class="ip-ranking">
                            <div class="chart-title">IP访问排名</div>
                            <div id="ipRankingList">
                                <!-- IP排名列表将通过JavaScript动态生成 -->
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 新旧访客比例分析 -->
                <div class="chart-container">
                    <div class="chart-title">访客类型分析</div>
                    <div class="chart-wrapper" id="visitorTypeChart"></div>
                    <div class="visitor-ratio">
                        <div class="ratio-item">
                            <div class="ratio-value ratio-new" id="newVisitorRatio">0%</div>
                            <div class="ratio-label">新访客</div>
                        </div>
                        <div class="ratio-item">
                            <div class="ratio-value ratio-return" id="returnVisitorRatio">0%</div>
                            <div class="ratio-label">回访客</div>
                        </div>
                    </div>
                </div>

                <!-- 访问时段分析 -->
                <div class="chart-container">
                    <div class="chart-title">24小时访问分布</div>
                    <div class="chart-wrapper" id="hourlyChart"></div>
                </div>
            </div>
        </main>
    </div>

    <script>
        // 初始化ECharts实例
        let dailyChart, ipRegionChart, visitorTypeChart, hourlyChart;
        
        // 访客统计数据
        let visitorData = {
            summary: {},
            dailyData: [],
            geoDistribution: [],
            deviceStats: [],
            realtimeStats: {}
        };

        // 初始化页面
        document.addEventListener('DOMContentLoaded', function() {
            initCharts();
            loadData();
            setDefaultDates();
        });

        // 初始化图表
        function initCharts() {
            dailyChart = echarts.init(document.getElementById('dailyChart'));
            ipRegionChart = echarts.init(document.getElementById('ipRegionChart'));
            visitorTypeChart = echarts.init(document.getElementById('visitorTypeChart'));
            hourlyChart = echarts.init(document.getElementById('hourlyChart'));

            // 响应式调整
            window.addEventListener('resize', function() {
                dailyChart.resize();
                ipRegionChart.resize();
                visitorTypeChart.resize();
                hourlyChart.resize();
            });
        }

        // 设置默认日期范围（最近7天）
        function setDefaultDates() {
            const endDate = new Date();
            const startDate = new Date();
            startDate.setDate(startDate.getDate() - 7);

            document.getElementById('startDate').value = startDate.toISOString().split('T')[0];
            document.getElementById('endDate').value = endDate.toISOString().split('T')[0];
        }

        // 加载数据
        async function loadData() {
            try {
                const startDate = document.getElementById('startDate').value;
                const endDate = document.getElementById('endDate').value;
                
                // 从API获取数据
                const [summary, geoDistribution, deviceStats, realtimeStats] = await Promise.all([
                    visitorAnalytics.getSummary(startDate, endDate),
                    visitorAnalytics.getGeoDistribution(startDate, endDate),
                    visitorAnalytics.getDeviceStats(startDate, endDate),
                    visitorAnalytics.getRealTimeStats(24)
                ]);
                
                // 更新数据
                visitorData.summary = summary.data || {};
                visitorData.geoDistribution = geoDistribution.data || [];
                visitorData.deviceStats = deviceStats.data || [];
                visitorData.realtimeStats = realtimeStats.data || {};
                
                // 更新统计卡片
                updateStatsCards();
                
                // 渲染图表
                renderDailyChart();
                renderIpRegionChart();
                renderVisitorTypeChart();
                renderHourlyChart();
                
                // 渲染IP排名列表
                renderIpRanking();
                
            } catch (error) {
                console.error('加载访客统计数据失败:', error);
                // 显示错误信息
                showError('加载数据失败，请检查网络连接或稍后重试');
            }
        }
        
        // 显示错误信息
        function showError(message) {
            // 可以在这里添加错误提示UI
            console.error('访客统计错误:', message);
        }

        // 更新统计卡片
        function updateStatsCards() {
            const summary = visitorData.summary;
            
            document.getElementById('totalVisits').textContent = (summary.total_visits || 0).toLocaleString();
            document.getElementById('uniqueVisitors').textContent = (summary.unique_visitors || 0).toLocaleString();
            document.getElementById('avgDuration').textContent = formatDuration(summary.avg_session_duration || 0);
            document.getElementById('pageViews').textContent = (summary.page_views || 0).toLocaleString();
            document.getElementById('todayVisits').textContent = (summary.today_visits || 0).toLocaleString();
            document.getElementById('newVisitors').textContent = (summary.new_visitors || 0).toLocaleString();
            document.getElementById('bounceRate').textContent = (summary.bounce_rate || 0) + '%';
            document.getElementById('viewsPerVisitor').textContent = (summary.views_per_visitor || 0).toFixed(1);
        }
        
        // 格式化持续时间（秒转分钟）
        function formatDuration(seconds) {
            if (!seconds) return '0秒';
            const minutes = Math.floor(seconds / 60);
            const remainingSeconds = seconds % 60;
            
            if (minutes === 0) {
                return remainingSeconds + '秒';
            }
            return minutes + '分' + remainingSeconds + '秒';
        }

        // 渲染每日访问量图表
        function renderDailyChart() {
            // 从实时统计数据中获取每日数据
            const dailyStats = visitorData.realtimeStats.daily_stats || [];
            
            const dates = dailyStats.map(item => item.date);
            const visits = dailyStats.map(item => item.visits || 0);
            const uniqueVisitors = dailyStats.map(item => item.unique_visitors || 0);
            
            const option = {
                tooltip: {
                    trigger: 'axis',
                    formatter: function(params) {
                        let result = params[0].axisValue + '<br/>';
                        params.forEach(param => {
                            result += `${param.marker} ${param.seriesName}: ${param.value}<br/>`;
                        });
                        return result;
                    }
                },
                legend: {
                    data: ['访问量', '独立访客']
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    data: dates
                },
                yAxis: {
                    type: 'value'
                },
                series: [
                    {
                        name: '访问量',
                        type: 'line',
                        data: visits,
                        smooth: true,
                        lineStyle: {
                            width: 3
                        },
                        itemStyle: {
                            color: '#3498db'
                        }
                    },
                    {
                        name: '独立访客',
                        type: 'line',
                        data: uniqueVisitors,
                        smooth: true,
                        lineStyle: {
                            width: 3
                        },
                        itemStyle: {
                            color: '#e74c3c'
                        }
                    }
                ]
            };

            dailyChart.setOption(option);
        }

        // 渲染IP地域分布图表
        function renderIpRegionChart() {
            const geoDistribution = visitorData.geoDistribution;
            
            const option = {
                tooltip: {
                    trigger: 'item',
                    formatter: '{a} <br/>{b}: {c} ({d}%)'
                },
                legend: {
                    orient: 'vertical',
                    left: 'left',
                    data: geoDistribution.map(item => item.region)
                },
                series: [
                    {
                        name: '访问量',
                        type: 'pie',
                        radius: '70%',
                        center: ['50%', '60%'],
                        data: geoDistribution.map(item => ({
                            value: item.count || 0,
                            name: item.region
                        })),
                        emphasis: {
                            itemStyle: {
                                shadowBlur: 10,
                                shadowOffsetX: 0,
                                shadowColor: 'rgba(0, 0, 0, 0.5)'
                            }
                        },
                        itemStyle: {
                            borderRadius: 10,
                            borderColor: '#fff',
                            borderWidth: 2
                        }
                    }
                ]
            };

            ipRegionChart.setOption(option);
        }

        // 渲染访客类型图表
        function renderVisitorTypeChart() {
            const option = {
                tooltip: {
                    trigger: 'item',
                    formatter: '{a} <br/>{b}: {c}%'
                },
                series: [
                    {
                        name: '访客类型',
                        type: 'pie',
                        radius: ['40%', '70%'],
                        avoidLabelOverlap: false,
                        itemStyle: {
                            borderRadius: 10,
                            borderColor: '#fff',
                            borderWidth: 2
                        },
                        label: {
                            show: false,
                            position: 'center'
                        },
                        emphasis: {
                            label: {
                                show: true,
                                fontSize: '20',
                                fontWeight: 'bold'
                            }
                        },
                        labelLine: {
                            show: false
                        },
                        data: []
                    }
                ]
            };

            visitorTypeChart.setOption(option);

            // 更新比例显示
            document.getElementById('newVisitorRatio').textContent = mockData.visitorType.new + '%';
            document.getElementById('returnVisitorRatio').textContent = mockData.visitorType.return + '%';
        }

        // 渲染24小时访问分布图表
        function renderHourlyChart() {
            const hours = Array.from({length: 24}, (_, i) => `${i}:00`);
            
            const option = {
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow'
                    }
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    data: hours
                },
                yAxis: {
                    type: 'value'
                },
                series: [
                    {
                        name: '访问量',
                        type: 'bar',
                        data: mockData.hourlyData,
                        itemStyle: {
                            color: '#3498db'
                        }
                    }
                ]
            };

            hourlyChart.setOption(option);
        }

        // 渲染IP排名列表
        function renderIpRanking() {
            const ipRankingList = document.getElementById('ipRankingList');
            ipRankingList.innerHTML = '';

            mockData.ipRanking.forEach((item, index) => {
                const ipItem = document.createElement('div');
                ipItem.className = 'ip-item';
                ipItem.innerHTML = `
                    <div class="ip-info">
                        <span class="ip-address">${item.ip}</span>
                        <span class="ip-region">${item.region}</span>
                    </div>
                    <span class="ip-count">${item.count}</span>
                `;
                ipRankingList.appendChild(ipItem);
            });
        }

        // 筛选数据
        function filterData() {
            const startDate = document.getElementById('startDate').value;
            const endDate = document.getElementById('endDate').value;
            
            if (!startDate || !endDate) {
                alert('请选择开始日期和结束日期');
                return;
            }

            if (new Date(startDate) > new Date(endDate)) {
                alert('开始日期不能晚于结束日期');
                return;
            }

            // 显示加载状态
            showLoading();
            
            // 模拟API请求延迟
            setTimeout(() => {
                // 在实际项目中，这里应该调用后端API获取筛选后的数据
                console.log('筛选日期范围:', startDate, '至', endDate);
                
                // 重新加载数据（这里使用模拟数据）
                loadData();
                hideLoading();
                
                alert('数据筛选完成');
            }, 1000);
        }

        // 重置筛选
        function resetFilter() {
            setDefaultDates();
            loadData();
        }

        // 显示加载状态
        function showLoading() {
            const charts = document.querySelectorAll('.chart-wrapper');
            charts.forEach(chart => {
                chart.innerHTML = '<div class="loading"><div class="spinner"></div></div>';
            });
        }

        // 隐藏加载状态
        function hideLoading() {
            // 图表会在loadData()中重新初始化
        }

        // 导出数据功能
        function exportData() {
            // 在实际项目中，这里应该调用后端API导出数据
            alert('数据导出功能（在实际项目中实现）');
        }

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 初始化导航栏
            const navbarManager = new NavbarManager();
        });

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 初始化导航栏
            const navbarManager = new NavbarManager();
        });
    </script>
</body>
</html>